package com.zhangyang;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/**
 * Created by ASUS on 2017/10/12.
 */
public class BufferProgram {

    /**
     * 主函数
     * @param args
     */
    public static void main(String[] args) throws Exception {
       //设置输入流
        FileInputStream fileInputStream =//输入流
                new FileInputStream("D:\\gupao\\txt\\文档.txt");

        //设置文件通道
        FileChannel fileChannel = fileInputStream.getChannel();

        ByteBuffer byteBuffer=ByteBuffer.allocate(10);
        outPut("初始化",byteBuffer);

        //读取数句
        fileChannel.read(byteBuffer);
        outPut("调用read",byteBuffer);

        byteBuffer.flip();
        outPut("调用flip",byteBuffer);

        Charset charset=Charset.forName("UTF-8");
        CharBuffer charBuffer=charset.decode(byteBuffer);
        System.out.println("charBuffer:"+charBuffer.toString());
//        while(byteBuffer.remaining()>0){
//            //有剩余的数
//            byte value=byteBuffer.get();
//            System.out.println("remain value:"+byteBuffer.get());
//        }

        byteBuffer.clear();
        outPut("调用clear",byteBuffer);
    }

    /**
     * 输出内容
     * @param outString
     * @param byteBuffer
     */
    private static void outPut(String outString, ByteBuffer byteBuffer) {
        System.out.println(outString + "  :");
        System.out.println("capacity:"+byteBuffer.capacity());
        System.out.println("position:" + byteBuffer.position());
        System.out.println("limit:"+byteBuffer.limit());
    }
}
